package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-08-07
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private BCryptPasswordEncoder bCrypt;

    //用户登录
    @Override
    public ResponseResult login(AdUserLoginDto dto) {

        String name = dto.getName();
        String password = dto.getPassword();
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName, name);
        AdUser adUser = this.getOne(wrapper);
        if (adUser == null) {
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        boolean matches = bCrypt.matches(password, adUser.getPassword());
        if (!matches) {
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Integer status = adUser.getStatus();
        if (status != 9) {
            throw new LeadException(AppHttpCodeEnum.AD_USER_UNAVAILABLE);
        }
        Map<String, Object> map = new HashMap<>();
        adUser.setLoginTime(new Date());
        this.updateById(adUser);
        AdUserDto adUserDto = BeanHelper.copyProperties(adUser, AdUserDto.class);
        String token = JwtUtils.generateTokenExpireInMinutes(adUserDto.getId(), 120);
        map.put("user", adUserDto);
        map.put("token", token);

        return ResponseResult.ok(map);
    }
}
